package com.atguigu.config;

import com.atguigu.bean.Yellow;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.util.StringValueResolver;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

/**
 * Profile:
 *      Spring 为我们提供了可以根据当前的环境，动图激活和创建一系列组件的功能
 *      开发、测试、生产环境
 *      @Profile:指定组件在哪个环境下才能被注册到容器中，不指定，任何环境下都是可以使用的
 *      1）、加了环境标识的bean，只有这个环境被激活的时候才能注册这个bean。默认是default环境
 *      2)、标注在配置类上，只有是指定的环境创建容器的时候，整个配置类里面的所有配置才能开始生效
 *      3）、没有标注环境标识的bean在，任何环境下都是生效的
 *
 */
@PropertySource(value = {"classpath:dbConfig.properties"})
@Configuration
public class MainConfigOfProfile implements EmbeddedValueResolverAware {
    @Value("${db.user}")
    private String user;
    private String jdbcDriver;

    @Profile("test")
    @Bean
    public Yellow yellow(){
        return new Yellow();
    }
    @Bean("devDataSource")
    @Profile("dev")
    public DataSource dataSourceTest(@Value("${db.password}")String password) throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setJdbcUrl("jdbc:mysql://192.87.18.32:3306/test");
        dataSource.setUser(user);
        dataSource.setPassword(password);
        dataSource.setDriverClass(jdbcDriver);
        return dataSource;
    }

    @Bean("testDataSource")
    @Profile("test")
    public DataSource dataSourceDev(@Value("${db.password}")String password) throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setJdbcUrl("jdbc:mysql://192.87.18.32:3306/test");
        dataSource.setUser(user);
        dataSource.setPassword(password);
        dataSource.setDriverClass(jdbcDriver);
        return dataSource;
    }
    @Bean("prodDataSource")
    @Profile("prod")
    public DataSource dataSourcePro(@Value("${db.password}")String password) throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setJdbcUrl("jdbc:mysql://192.87.18.32:3306/test");
        dataSource.setUser(user);
        dataSource.setPassword(password);
        dataSource.setDriverClass(jdbcDriver);
        return dataSource;
    }

    @Override
    public void setEmbeddedValueResolver(StringValueResolver resolver) {
        String s = resolver.resolveStringValue("${db.driver}");
        jdbcDriver = s;
    }
}
